//
//  FreeViewController.swift
//  1604_LimitFree
//
//  Created by 千锋 on 16/9/26.
//  Copyright © 2016年 Mabin. All rights reserved.
//

import UIKit

class FreeViewController: LFBaseViewController {
    
    //分类的ID值
    private var cateId : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.greenColor()
        
        //上拉刷新
        addRedresh()
        
    }
    
    override func createMyNav() {
        
        addNavBarbutton("分类", target: self, action: "goToCateGory", isLeft: true)
        
        addnavTitle("免费")
        
        addNavBarbutton("设置", target: self, action: "goTosetting", isLeft: false)
    }
    
    //分类
    func goToCateGory()
    {
        let cateVC = CategoryViewController()
        cateVC.delegate = self
        cateVC.type = .Free
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(cateVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    func goTosetting()
    {
        let setVc = SettingViewController()
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(setVc, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    //下载
    override func downloaderData() {
        ProgressHUD.showOnView(view)
        var urlString = String(format: kFreeUrl,curPage)
        if cateId != nil
        {
            urlString = urlString.stringByAppendingString("&category_id=\(cateId!)")
        }
        let download = LFDownloader()
        download.delegate = self
        download.downloadWithURLString(urlString)
    }
    
    //MARK:表格的方法
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellId = "freeCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? FreeCell
        if cell == nil
        {
            cell = NSBundle.mainBundle().loadNibNamed("FreeCell", owner: nil, options: nil).last as? FreeCell
        }
        let model = dataArray[indexPath.row] as! LimitModel
        cell?.config(model, atindex: indexPath.row+1)
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let model = dataArray[indexPath.row] as! LimitModel
        
        let detailVC = DetailViewController()
        detailVC.appId = model.applicationId
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
}

extension FreeViewController : LFDownloaderDelegate
{
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        ProgressHUD.hideAfterFailOnView(view)
    }
    
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        //下拉刷新,清空数组
        if curPage == 1
        {
            dataArray.removeAllObjects()
        }
        
        //进行JSON解析
        let result = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        if result.isKindOfClass(NSDictionary)
        {
            let dict = result as! Dictionary<String,AnyObject>
            let array = dict["applications"] as! Array<Dictionary<String,AnyObject>>
            for appDict in array
            {
                let model = LimitModel()
                model.setValuesForKeysWithDictionary(appDict)
                dataArray.addObject(model)
            }
            
            dispatch_async(dispatch_get_main_queue(), {
                self.tableView?.reloadData()
                self.tableView?.headerView?.endRefreshing()
                self.tableView?.footerView?.endRefreshing()
                ProgressHUD.hideAfterSuccessOnView(self.view)
                
            })
        }
    }
}

//MARK:分类的代理方法
extension FreeViewController : CategoryViewControllerDelegate
{
    func didClickCateId(cateId: String, cateName: String) {
        
        //标题
        var title = "免费-"+cateName
        if cateName == "全部"
        {
            title = "免费"
        }
        addnavTitle(title)
        
        //下载
        self.cateId = cateId
        curPage = 1
        downloaderData()
    }
}

